<script setup>
import { ref, onMounted, computed, watch } from "vue";
import {Delete, Edit, Plus, Upload, Search, Refresh} from "@element-plus/icons";
import {ElMessage, ElMessageBox} from "element-plus";
import zhCn from 'element-plus/es/locale/lang/zh-cn';

const props = defineProps({
  // 父组件传递的参数
  filterGroupId: {
    type: [Number, String, null],
    default: null
  }
});
const keywords = ref([]);
const dialogFormVisible = ref(false);
const form = ref({
  groupId: "",
  keywords: "",
  tipInfo: "",
});
const keywordGroups = ref([]);
const isEditMode = ref(false);
const currentEditId = ref("");
const searchText = ref("");
const groupId = ref("");

// 分页相关
const currentPage = ref(1);
const pageSize = ref(20);
const totalKeywords = ref(0);

// 中文语言配置
const locale = zhCn;

const addKeyword = () => {
  getGroupList();
  dialogFormVisible.value = true;
}

const saveDialogForm = () => {
  // 处理关键词，支持换行、空格、逗号分割
  let keywords = form.value.keywords.toString()
      .split(/[\n\s,]+/)  // 使用正则表达式按换行符、空格、逗号分割
      .map(k => k.trim()) // 去除每个关键词前后的空格
      .filter(k => k);    // 过滤掉空字符串

  const tipInfo = form.value.tipInfo;
  const groupId = form.value.groupId;

  // 如果没有选择分组或没有输入关键词，则返回
  if (!groupId || keywords.length === 0) {
    ElMessage.error("请选择分组并输入关键词");
    return;
  }

  // 获取分组颜色
  const groupColor = keywordGroups.value.find(group => group.id === groupId)?.color || '#409eff';

  if (isEditMode.value) {
    // 编辑模式：更新现有关键词
    chrome.storage.local.get(['keywords'], (result) => {
      const existingKeywords = result.keywords || [];

      // 找到要编辑的关键词并更新它
      const updatedKeywords = existingKeywords.map(keyword => {
        if (keyword.id === currentEditId.value) {
          return {
            ...keyword,
            keyword: keywords[0], // 编辑时只处理第一个关键词
            tip: tipInfo || '',
            groupId: groupId,
            color: groupColor
          };
        }
        return keyword;
      });

      chrome.storage.local.set({ keywords: updatedKeywords }, () => {
        loadKeywords(); // 改为调用loadKeywords来保持筛选状态
        ElMessage.success("关键词更新成功");
        closeDialogForm();
      });
    });
  } else {
    // 新增模式：构造要保存的数据结构
    const keywordData = keywords.map((keyword) => ({
      id: generateId(),
      keyword: keyword,
      tip: tipInfo || '',
      groupId: groupId,
      color: groupColor
    }));

    // 保存到存储中
    chrome.storage.local.get(['keywords'], (result) => {
      const existingKeywords = result.keywords || [];
      const newKeywords = [...existingKeywords, ...keywordData];

      chrome.storage.local.set({ keywords: newKeywords }, () => {
        loadKeywords(); // 改为调用loadKeywords来保持筛选状态
        ElMessage.success("关键词保存成功");
        closeDialogForm();
      });
    });
  }
};

const closeDialogForm = () => {
  form.value = {
    groupId: "",
    keywords: "",
    tipInfo: ""
  };
  isEditMode.value = false;
  currentEditId.value = "";
  dialogFormVisible.value = false;
};

const editKeyword = (keywordId) => {
  const keywordToEdit = keywords.value.find(keyword => keyword.id === keywordId);

  if (keywordToEdit) {
    getGroupList();

    // 设置表单数据
    form.value = {
      groupId: keywordToEdit.groupId,
      keywords: keywordToEdit.keyword,
      tipInfo: keywordToEdit.tip
    };

    // 设置编辑模式标识
    isEditMode.value = true;
    currentEditId.value = keywordId;

    // 打开对话框
    dialogFormVisible.value = true;
  }
};

const deleteKeyword = (keywordId) => {
  // 添加确认弹窗
  ElMessageBox.confirm(
      '确定要删除这个关键词吗？此操作不可撤销。',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    // 从存储中删除指定ID的关键词
    chrome.storage.local.get(['keywords'], (result) => {
      const existingKeywords = result.keywords || [];
      const updatedKeywords = existingKeywords.filter(keyword => keyword.id !== keywordId);

      chrome.storage.local.set({ keywords: updatedKeywords }, () => {
        // 更新关键词列表
        loadKeywords();
        ElMessage.success("关键词删除成功");
      });
    });
  }).catch(() => {
    // 取消删除
    ElMessage.info('已取消删除');
  });
}

// 根据分组筛选关键词
const filterKeywordsByGroup = (newGroupId) => {
  if (newGroupId) {
    groupId.value = newGroupId;
    currentPage.value = 1; // 重置到第一页
    loadKeywords();
  } else {
    reset();
  }
};

const getGroupList = () => {
  // 获取分组列表
  chrome.storage.local.get(['groups'], (result) => {
    keywordGroups.value = result.groups || [];
    console.log("当前所有分组:", keywordGroups.value);
  });
};

// 生成唯一ID
function generateId() {
  return Date.now().toString(36) + Math.random().toString(36).substr(2);
}

// 核心修复：分离搜索逻辑和加载逻辑
const loadKeywords = () => {
  // 获取关键词列表
  chrome.storage.local.get(['keywords'], (result) => {
    let allKeywords = result.keywords || [];

    // 根据搜索文本进行模糊查询
    if (searchText.value) {
      const searchTextLower = searchText.value.toString().toLowerCase();
      allKeywords = allKeywords.filter(keyword =>
          keyword.keyword.toLowerCase().includes(searchTextLower) ||
          (keyword.tip && keyword.tip.toLowerCase().includes(searchTextLower))
      );
    }

    // 根据分组ID进行筛选
    if (groupId.value) {
      allKeywords = allKeywords.filter(keyword => keyword.groupId === groupId.value);
    }

    // 更新总数和分页数据
    totalKeywords.value = allKeywords.length;

    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    keywords.value = allKeywords.slice(start, end);

    console.log("加载关键词:", keywords.value);
  });
};

// 搜索函数 - 重置页码到第一页
const search = () => {
  currentPage.value = 1; // 搜索时重置到第一页
  loadKeywords();
};

const reset = () => {
  searchText.value = "";
  groupId.value = "";
  currentPage.value = 1;
  loadKeywords();
};

const clearAll = () => {
  // 添加确认弹窗
  ElMessageBox.confirm(
      '确定要清空所有关键词吗？此操作不可撤销。',
      '确认清空',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    // 清空关键词列表
    chrome.storage.local.set({ keywords: [] }, () => {
      loadKeywords();
    })
  })
}

const batchImport = () => {
  // 实现逻辑
  ElMessage.info('批量导入功能开发中...');
}

// 分页处理 - 直接调用loadKeywords，不重置页码
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  currentPage.value = 1; // 切换页面大小时重置到第一页
  loadKeywords();
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  loadKeywords(); // 直接加载，不重置页码
}

// 计算属性
const groupNameMap = computed(() => {
  const map = {};
  keywordGroups.value.forEach(group => {
    map[group.id] = group.name;
  });
  return map;
});

// 监听筛选条件变化
watch(() => props.filterGroupId, (newGroupId) => {
  filterKeywordsByGroup(newGroupId);
}, { immediate: true });

onMounted(() => {
  getGroupList();
  loadKeywords();
});
</script>

<template>
  <el-config-provider :locale="locale">
    <div class="keyword-manager">
      <!-- 搜索和操作区域 -->
      <el-card class="search-section">
        <div class="search-content">
          <el-row :gutter="16" align="middle">
            <el-col :xs="24" :sm="12" :md="8">
              <el-input
                  v-model="searchText"
                  placeholder="请输入关键词或提示信息"
                  clearable
                  @keyup.enter="search"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </el-col>

            <el-col :xs="24" :sm="12" :md="6">
              <el-select
                  v-model="groupId"
                  placeholder="选择分组"
                  clearable
                  style="width: 100%"
              >
                <el-option
                    v-for="item in keywordGroups"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                >
                  <div class="group-option">
                    <span class="color-dot" :style="{ backgroundColor: item.color }"></span>
                    <span>{{ item.name }}</span>
                  </div>
                </el-option>
              </el-select>
            </el-col>

            <el-col :xs="12" :sm="6" :md="4">
              <el-button type="primary" @click="search" style="width: 100%">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
            </el-col>

            <el-col :xs="12" :sm="6" :md="4">
              <el-button @click="reset" style="width: 100%">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-col>
          </el-row>
        </div>
      </el-card>

      <!-- 操作按钮区域 -->
      <el-card class="action-section">
        <div class="action-content">
          <el-space wrap :size="16">
            <el-button type="primary" @click="addKeyword">
              <el-icon><Plus /></el-icon>
              添加关键词
            </el-button>
            <el-button type="success" @click="batchImport">
              <el-icon><Upload /></el-icon>
              批量导入
            </el-button>
            <el-button type="danger" @click="clearAll">
              <el-icon><Delete /></el-icon>
              清空所有
            </el-button>
          </el-space>

          <div class="stats-info">
            共 {{ totalKeywords }} 个关键词
          </div>
        </div>
      </el-card>

      <!-- 关键词列表 -->
      <el-card class="list-section">
        <template #header>
          <div class="list-header">
            <span>关键词列表</span>
            <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="totalKeywords"
                layout="sizes, prev, pager, next, total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
          </div>
        </template>

        <div class="keywords-grid">
          <div
              v-for="item in keywords"
              :key="item.id"
              class="keyword-card"
          >
            <div class="card-header">
              <div class="keyword-main">
                <div class="color-indicator" :style="{ backgroundColor: item.color }"></div>
                <span class="keyword-text" :title="item.keyword">{{ item.keyword }}</span>
              </div>
              <div class="card-actions">
                <el-tooltip content="编辑" placement="top">
                  <el-button size="small" type="primary" link @click="editKeyword(item.id)">
                    <el-icon><Edit /></el-icon>
                  </el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button size="small" type="danger" link @click="deleteKeyword(item.id)">
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </el-tooltip>
              </div>
            </div>

            <div v-if="item.tip" class="keyword-tip" :title="item.tip">
              {{ item.tip }}
            </div>

            <div class="keyword-meta">
              <el-tag size="small" effect="plain">
                {{ groupNameMap[item.groupId] || '未分组' }}
              </el-tag>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="keywords.length === 0" class="empty-state">
          <el-empty description="暂无关键词" />
        </div>

        <!-- 底部分页 -->
        <template #footer>
          <div class="list-footer">
            <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="totalKeywords"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
          </div>
        </template>
      </el-card>

      <!-- 添加/编辑对话框 -->
      <el-dialog
          :title="isEditMode ? '编辑关键词' : '添加关键词'"
          v-model="dialogFormVisible"
          width="600px"
      >
        <el-form :model="form" label-width="100px">
          <el-form-item label="分组名称">
            <el-select v-model="form.groupId" placeholder="请选择分组" style="width: 100%">
              <el-option
                  v-for="item in keywordGroups"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              >
                <div class="group-option">
                  <span class="color-dot" :style="{ backgroundColor: item.color }"></span>
                  <span>{{ item.name }}</span>
                </div>
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="关键词">
            <el-input
                v-model="form.keywords"
                type="textarea"
                :rows="3"
                placeholder="请输入关键词，多个关键词可以用换行、空格或逗号分隔"
                show-word-limit
                maxlength="500"
            />
          </el-form-item>

          <el-form-item label="提示信息">
            <el-input
                v-model="form.tipInfo"
                type="textarea"
                :rows="2"
                placeholder="请输入提示信息（可选）"
                show-word-limit
                maxlength="200"
            />
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button @click="closeDialogForm">取消</el-button>
          <el-button type="primary" @click="saveDialogForm">
            {{ isEditMode ? '更新' : '确定' }}
          </el-button>
        </template>
      </el-dialog>
    </div>
  </el-config-provider>
</template>

<style scoped>
.keyword-manager {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.search-section,
.action-section {
  margin-bottom: 16px;
}

.search-content,
.action-content {
  padding: 16px 20px;
}

.action-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.stats-info {
  color: #909399;
  font-size: 14px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 4px;
}

.keywords-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
}

.keyword-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  background: #fff;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.keyword-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-color: #409eff;
  transform: translateY(-2px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 12px;
}

.keyword-main {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
  min-width: 0;
}

.color-indicator {
  width: 16px;
  height: 16px;
  border-radius: 4px;
  border: 2px solid #f0f0f0;
  flex-shrink: 0;
}

.keyword-text {
  font-weight: 500;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
}

.card-actions {
  display: flex;
  gap: 4px;
  flex-shrink: 0;
}

.keyword-tip {
  color: #606266;
  font-size: 13px;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.keyword-meta {
  display: flex;
  justify-content: flex-start;
}

.list-footer {
  display: flex;
  justify-content: center;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.empty-state {
  padding: 40px 0;
}

.group-option {
  display: flex;
  align-items: center;
  gap: 8px;
}

.color-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  border: 1px solid #ddd;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .keyword-manager {
    padding: 16px;
  }

  .keywords-grid {
    grid-template-columns: 1fr;
  }

  .action-content {
    flex-direction: column;
    align-items: stretch;
  }

  .stats-info {
    text-align: center;
  }

  .list-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
}

@media (max-width: 480px) {
  .search-content .el-row > .el-col {
    margin-bottom: 12px;
  }

  .keyword-card {
    padding: 12px;
  }
}
</style>